package com.cnswhy.cloud.server.comsumer.consumer;

import com.cnswhy.cloud.common.redis.annotation.RedisLock;
import com.cnswhy.cloud.common.redis.service.IdGeneratorService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.mq.SpellDayendCancelMsg;
import com.cnswhy.cloud.server.comsumer.event.ResetSpellPriceOrderEvent;
import com.cnswhy.cloud.server.comsumer.event.SpellDayendEvent;
import com.cnswhy.cloud.server.core.entity.SpellPrice;
import com.cnswhy.cloud.server.core.service.spell.SpellPriceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class SpellPriceConsumer implements SpellDayendEvent, ResetSpellPriceOrderEvent {
    @Autowired
    SpellPriceService spellPriceService;
    @Autowired
    IdGeneratorService idGeneratorService;
    @Autowired
    RedisService redisService;
    @Override
    @RedisLock(name = "SpellPriceConsumer")
    public void dayend(SpellDayendCancelMsg spellDayendCancelMsg) {
        SpellDayendCancelMsg spellDayendCancelMsg1 = (SpellDayendCancelMsg)redisService.get("SpellPriceConsumer" + spellDayendCancelMsg.getSettDate());
        if(spellDayendCancelMsg1 == null){
            redisService.set("SpellPriceConsumer" + spellDayendCancelMsg.getSettDate(),spellDayendCancelMsg,300L);
            log.info("拼团日终处理:{} 重新生成新的拼团单号",spellDayendCancelMsg.getSettDate());
            reset();
        }else{
        }

    }

    @Override
    @RedisLock(name = "SpellPriceConsumer")
    public void reset(SpellDayendCancelMsg dayendCancelMsg) {
        log.info("手工重置生成拼团订单组",dayendCancelMsg.getSettDate());
        reset();
    }
    private void reset(){
        List<SpellPrice> spellPrices = spellPriceService.list();
        for(SpellPrice spellPrice : spellPrices){
            if(spellPrice != null){
                spellPrice.setNewSpellOrderId(idGeneratorService.genCommonIdString());
                spellPriceService.updateById(spellPrice);
            }
            log.info("价格区间:{} 新增拼团单号:{}", spellPrice.getTitle(),spellPrice.getNewSpellOrderId());
        }
    }
}
